package com.easylinkin.linkappapi.security.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.easylinkin.linkappapi.common.constant.CommonConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.easylinkin.bases.redis.util.RedisUtil;
import com.easylinkin.linkappapi.security.entity.LinkappUser;
import com.easylinkin.linkappapi.security.service.LinkappUserService;
import com.easylinkin.sm.constant.LogConstant.Module;
import com.easylinkin.sm.entity.Log;
import com.easylinkin.sm.service.LogService;

import lombok.extern.slf4j.Slf4j;
import site.morn.boot.web.Responses;
import site.morn.framework.context.AccountContext;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

/**
 * 认证成功处理者
 *
 * @author timely-rain
 * @since 1.2.0, 2019/8/29
 */
@Slf4j
@Component
public class LinkappMiniAppAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

  @Autowired
  private LinkappUserService userService;

  @Autowired
  private LogService logService;

  @Autowired
  private RedisUtil redisUtil;
  
  @Override
  public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
      Authentication authentication) {

		String sessionKey = request.getParameter("sessionKey");
		LinkappUser user = (LinkappUser) redisUtil.get(sessionKey + "_miniapplogin");
		request.setAttribute("username", user.getUsername());
		Log log = new Log();
		log.setModuleId(Long.parseLong(Module.LOGIN));
		log.setIp(request.getRemoteAddr());
		log.setContent("用户登录");
		log.setStatus(true);
		log.setDisplay(true);
		logService.add(log);

		// 清空登录缓存
		AccountContext.cacheGroup().clearKey(authentication.getName());
		
		JSONObject json = new JSONObject();
	  	HttpSession session = request.getSession(false);
	  	if(session != null){
			json.put("token", session.getId()); // 登录成功后把sessionId返回
			session.setMaxInactiveInterval(CommonConstant.SESSION_TIME_DEFAULT);;
		}
		RestMessage message = RestBuilders.successBuilder().data(json).build();
		Responses.standard(response).respond(message);
		
  }
}
